﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class EditCDKForm : Form
    {
        private int cdkId;

        public EditCDKForm(int cdkId)
        {
            InitializeComponent();
            this.cdkId = cdkId;
        }

        private void EditCDKForm_Load(object sender, EventArgs e)
        {
            LoadCDKData();
        }

        private void LoadCDKData()
        {
            using (SqlConnection conn = DBConnection.CreateConnection())
            {
                DBConnection.Open(conn);
                SqlCommand cmd = new SqlCommand($"SELECT * FROM CDK WHERE CDKId = {cdkId}", conn);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    txtCDK.Text = reader["CDK"].ToString();
                    chkIsAvailable.Checked = Convert.ToBoolean(reader["IsAvailable"]);
                    numAvailableUses.Value = Convert.ToInt32(reader["AvailableUses"]);
                }
                DBConnection.Close(conn);
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = DBConnection.CreateConnection())
            {
                DBConnection.Open(conn);
                SqlCommand cmd = new SqlCommand("UPDATE CDK SET CDK = @cdk, IsAvailable = @isAvailable, AvailableUses = @availableUses WHERE CDKId = @cdkId", conn);
                cmd.Parameters.AddWithValue("@cdkId", cdkId);
                cmd.Parameters.AddWithValue("@cdk", txtCDK.Text);
                cmd.Parameters.AddWithValue("@isAvailable", chkIsAvailable.Checked);
                cmd.Parameters.AddWithValue("@availableUses", Convert.ToInt32(numAvailableUses.Value));
                cmd.ExecuteNonQuery();
                DBConnection.Close(conn);
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
